package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IAppointmentService;

import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;


    @Autowired
    private IAppointmentService appointmentService;         // 预约单业务

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {


        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);

        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }








    /**
     * 流程部署
     * @param path
     * @param bpmnType
     * @param info
     */
    @Override
    public void deploy(String path, String bpmnType, String info) throws IOException {
        // 1.判断程序是否为空



        // 2.部署流程

        String lowerStr = path.toLowerCase();
        // 文件流:读取之前上传的流程文件
        File bpmnFile = new File(SystemConfig.getProfile(), path);
        FileInputStream inputStream = new FileInputStream(bpmnFile);

        Deployment deploy = null;
        if (lowerStr.endsWith("zip")) {

            deploy = repositoryService.createDeployment()
                    .addZipInputStream(new ZipInputStream(inputStream))
                    .deploy();
        } else if (lowerStr.endsWith("bpmn")) {
            deploy = repositoryService.createDeployment()
                    // 参数1资源名称,参数2流程文件流
                    .addInputStream(path, inputStream)
                    .deploy();
        }
        if (deploy == null) {
            throw new BusinessException("部署失败");
        }


        // 3.创建流程定义对象
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnName(deploy.getName());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());
        bpmnInfo.setInfo(info);

        // 获取activiti中流程定义对象的:ActProcessId,ActProcessKey
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .latestVersion()
                .singleResult();

        // 部署对象无法获取name值,使用定义对象name
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);

        inputStream.close();
    }

    @Override
    public InputStream readResource(String deploymentId, String type) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .latestVersion()
                .singleResult();

        InputStream inputStream = null;
        if ("xml".equalsIgnoreCase(type)) {
            inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());

        } else if ("png".equalsIgnoreCase(type)) {
            // 根据流程文件使用代码方式画出来
            BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }

        return inputStream;
    }


    /**
     * 流程定义中删除按钮操作
     * @param id
     */
    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = this.get(id);
        // 没删之前先查出来 查出来再删tmd
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .latestVersion()
                .singleResult();

        // TODO 当需要删除流程定义时,系统可能流转很多该流程定义的流程实例对象: ProcessInstance
        // TODO 此时删除之前,需要将这些处理中流程数据恢复到初始化状态

        // 1.部署流程相关的数据删除 (流程部署表/流程定义表) activiti7的
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);


        // 2.删除当初上的文件
        /*ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .latestVersion()
                .singleResult();*/
        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        if (file.exists()) {
            file.delete();
        }


        // 3.流程定义对象(BpmnInfo)
        bpmnInfoMapper.deleteByPrimaryKey(id);

    }

    @Override
    public BpmnInfo queryByBpmnType(String bpmnType) {

        return bpmnInfoMapper.selectbyBpmnType(bpmnType);
    }
}
